﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using OestsCommon.Model;
using OestsDataBase;
using OestsCommon.TcpNet;
using OestsServer.Managers;

/// <summary>
/// 用来跟客户端做通信 
/// </summary>
namespace OestsServer.Net
{
	public class ClientChannel
	{
		private Server server;
		private TcpServer tcpServer;
		private User _user;

        /// <summary>
        /// 客户端类型，基值对应项目id，每个项目的任务信息，房间信息等不一样
        /// </summary>
		public ClientType ClientType { get; set; }

		public User User { get { return _user; } }

		//获取IP地址
		public IPAddress IP
		{
			get { return tcpServer.GetIPAddress(); }
		}

		/// <summary>
		/// 实时更新线程
		/// </summary>
		//private Thread _updateThread;

        public ClientChannel()
        {
            Room.SendToStudentSignal.AddListener(SendToStudent);
        }

		public ClientChannel(Server server, Socket socket)
		{
            Room.SendToStudentSignal.AddListener(SendToStudent);
            this.server = server;
			tcpServer = new TcpServer(socket, ReceiveCallback);
			tcpServer.AsynRecive();

			//  _updateThread = new Thread(Update);

			// _updateThread.IsBackground = true;
			//_updateThread.Start();
		}

        private void SendToStudent(int stuID, Response packet)
        {
            if(User is Student)
            {
                if(User.DBid == stuID)
                {
                    Send(packet);
                }
            }
        }



		/// <summary>
		/// 接收到消息的回调执行函数
		/// </summary>
		/// <param name="message"></param>
		private void ReceiveCallback(Request p)
		{
			string str = DateTime.Now.ToLongTimeString();
			string userIP = tcpServer.GetIPAddress().ToString();

			if (p.RequestCode == PacketKey.DisConnected)
			{
				ClientManager.Instance.DisConnectedHandler(this);
				tcpServer.Close();
				return;
			}
			Console.WriteLine("\n--->" + str + "  收到from(" + userIP + ")： " + p.RequestCode + "+" + p.RequestSubCode + "+" + p.DataStr + "\n");

			Server.Instance.Parse(this, p);

		}

		/// <summary>
		/// 发送
		/// </summary>
		/// <param name="packetKey"></param>
		/// <param name="packetMsg"></param>
		//public void Send(PacketKey packetKey, object packetMsg)
		//{
		//    tcpCommon.AsynSend(new Packet(packetKey, packetMsg));
		//}


		public void Send(Response packet)
		{
			tcpServer.AsynSend(packet);
			string str = DateTime.Now.ToLongTimeString();
			string userIP = tcpServer.GetIPAddress().ToString();
			Console.WriteLine("\n--->" + str + "  发送数据to(" + userIP + ")： " + packet.ResponseCode + "" + packet.ResponseSubCode + "" + packet.ReturnCode + "" + packet.DataStr + "\n");
		}

		private void Update()
		{
			while (true)
			{
				Thread.Sleep(5000);//刷新频率 5s
				#region 记录当前时间到数据库

				UpdateLogoutTime();

				#endregion
			}

		}

		public void UpdateLoginTime()
		{
			_user.LoginTime = DateTime.Now;
			switch (_user.Type)
			{
				case UserType.Admin:
					AdminDAL.SaveLoginTime(_user.DBid);
					break;
				case UserType.Teacher:
					TeacherDAL.SaveLoginTime(_user.DBid);
					break;
				case UserType.Student:
					StudentDAL.SaveLoginTime(_user.DBid);
					break;
			}

		}

		public void UpdateLogoutTime()
		{
			_user.LogoutTime = DateTime.Now;
			switch (_user.Type)
			{
				case UserType.Admin:
					AdminDAL.SaveLogoutTime(_user.DBid);
					break;
				case UserType.Teacher:
					TeacherDAL.SaveLogoutTime(_user.DBid);
					break;
				case UserType.Student:
					StudentDAL.SaveLogoutTime(_user.DBid);
					break;
			}
		}

		public void SetUserData(User user)
		{
			_user = user;
		}

		public bool CheckUserIsExist( UserType uType, int userDbId)
		{
			return ClientManager.Instance.CheckUserIsExist(uType, userDbId);
		}

		/// <summary>
		/// 返回教师id
		/// </summary>
		/// <returns></returns>
		public int GetTeacherId()
		{
			if (_user is Teacher)
			{
				return (_user as Teacher).DBid;
			}
			return -1;
		}

        /// <summary>
        /// 房间广播
        /// </summary>
        /// <param name="clientMe"></param>
        /// <param name="packet"></param>
        public void BroadcastInRoomButMe(Response packet)
        {
            if(User is Student)
            {
                Room room = (User as Student)._room;
                for (int j = 0; j < room.Members.Count; j++)
                {
                    ClientChannel client = ClientManager.Instance.GetStudentClientByStudentId(room.Members[j].MemberId);
                    if (client != null)
                    {
                        if (client.User.DBid != User.DBid)
                        {
                            client.Send(packet);
                        }
                    }
                }
            }
          
        }
    }

}
